package com.lagou.product_springcloud.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class ProductsProducer {
    private static String topic = "lagou";
    private static Properties properties;
    private static KafkaProducer<String, String> kafkaProducer;
    static {
        properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.20:9092, 192.168.200.20:9092, 192.168.200.20:9092");
        //网络传输对key和value进行序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //创建消息生产对象，从properties对象或从properties文件中加载信息
        kafkaProducer = new KafkaProducer<>(properties);
    }

    public static String sendMsg(Integer id){
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, id.toString());
        kafkaProducer.send(record);
        return "消息发送成功:" + id;
    }

    public static void close(){
        kafkaProducer.close();
    }
}
